#include <unistd.h>
#include <signal.h>


#include <iostream>

using std::cout;
using std::endl;

#include <workflow/WFFacilities.h>
#include <workflow/WFTaskFactory.h>
#include <workflow/RedisMessage.h>

static WFFacilities::WaitGroup waitGroup(1);

void sighandler(int num)
{
    printf("sig number %d is comming\n", num);
    waitGroup.done();
}

void redisCallback(WFRedisTask * redistask)
{
    int * pnumber = (int*)redistask->user_data;
    cout << "pnumber:" << pnumber << endl;
    cout << "*pnumber:" << *pnumber << endl;
    cout << "redisCallback is running" << endl;


    //1. 错误的检测
    int state = redistask->get_state();
    int error = redistask->get_error();

    switch(state) {
    case WFT_STATE_SYS_ERROR:
        printf("system error: %s\n", strerror(error)); break;
    case WFT_STATE_DNS_ERROR:
        printf("dns error: %s\n", gai_strerror(error)); break;
    case WFT_STATE_SUCCESS:
        break;
    }

    if(state != WFT_STATE_SUCCESS) {
        printf("error occurs!\n");
        return;
    }

    printf("task success\n");
    //2. 获取请求信息
    auto req = redistask->get_req();
    std::string command;
    std::vector<std::string> params;
    req->get_command(command);
    req->get_params(params);
    cout << command << " ";
    for(auto & param : params) {
        cout << param << " ";
    }
    cout << endl;

    //3. 获取响应信息
    auto resp = redistask->get_resp();
    protocol::RedisValue result;
    resp->get_result(result);

    //遍历RedisValue的数据
    if(result.is_string()) {
        cout << "value is string, value:"
             << result.string_value() << endl;
    } else if(result.is_int()) {
        cout << "value is integer, value:"
             << result.int_value() << endl;
        //添加第二个redisTask
        std::string url("redis://127.0.0.1:6379");
        auto redisTask2 = WFTaskFactory::create_redis_task(url, 1, redisCallback);
        redisTask2->get_req()->set_request("HGETALL", {"student"});

        //将任务1中的共享数据传递给任务2
        redisTask2->user_data = redistask->user_data;
        //通过任务本身获取其所在的序列
        series_of(redistask)->push_back(redisTask2);
    } else if(result.is_array()) {
        cout << "value is array:" << endl;
        for(size_t i = 0; i < result.arr_size(); ++i) {
            cout << "arr[" << i << "]:" 
                 << result.arr_at(i).string_value() << endl;
        }
    }
}

void test0()
{
    signal(SIGINT, sighandler);
    std::string url = "redis://127.0.0.1:6379";
    
    int number = 1;

    //创建Redis任务
    auto redisTask = WFTaskFactory::create_redis_task(url, 1, redisCallback);

    //将test0函数栈空间的数据保存到任务1中
    redisTask->user_data = &number;

    //设置任务的属性
    auto req = redisTask->get_req();
    req->set_request("HSET", {"student", "name", "Jackie", "age", "30"});
    //交给框架来调度运行
    redisTask->start();
    waitGroup.wait();

}


int main()
{
    test0();
    return 0;
}

